//------------------------------------------------------------------------------
// <copyright file="OpenComboBoxBehavior.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls.Primitives;

namespace DotBeer.UI.WPFClient.Behaviors
{
    public class OpenComboBoxBehavior : Behavior<ComboBox>
    {
        Grid layoutRoot;

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
            this.layoutRoot.MouseEnter -= new MouseEventHandler(grid_MouseEnter);
            this.layoutRoot.MouseLeave -= new MouseEventHandler(grid_MouseLeave);
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            this.layoutRoot = VisualTreeHelper.GetChild(this.AssociatedObject, 0) as Grid;
            this.layoutRoot.MouseEnter += new MouseEventHandler(grid_MouseEnter);
            this.layoutRoot.MouseLeave += new MouseEventHandler(grid_MouseLeave);
        }

        private void grid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (this.AssociatedObject.Items.Count > 0)
                this.AssociatedObject.IsDropDownOpen = true;
        }

        private void grid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (this.AssociatedObject.Items.Count > 0)
                this.AssociatedObject.IsDropDownOpen = false;
        }
    }
}
